<template>
  <div class="video-watermark-container">
    <div class="input-section">
      <div class="button-container">
        <!-- <input type="file" @change="uploadVideo" class="upload-btn" accept="*"> -->
        <button @click="chooseFile">上传视频文件</button>
        <button @click="removeWatermark" class="remove-watermark-btn">
          去除水印
        </button>
        <button @click="clearRect" class="clear-btn">
          清除框
        </button>
      </div>
    </div>

    <div class="video-section" style="position: relative; width: 800px; height: 450px;">
      <canvas id="video-canvas" ref="canvasRef"
              style="position: absolute; top: 0; left: 0; z-index: 1;"></canvas>
      <video id="video" ref="videoRef" :src="videoUrl" controls class="video-player" @click="drawRect"
             @loadedmetadata="initCanvas"
             style="position: absolute; top: 0; left: 0; z-index: 0; width: 800px; height: 450px;"></video>
      <video :src="noWaterVideoUrl" controls class="video-player" @click="drawRect" v-show="noWaterVideoUrl"
             style="position: absolute; top: 460px; left: 0; z-index: 0; width: 800px; height: 450px;"></video>
    </div>
  </div>
</template>


<script>
import {
  postVideoRemoveWatermark,

} from '@/api/video'

import {
  uploadFile
} from '@/api/oss'

export default {
  name: 'VideoRemoveWater',
  data() {
    return {
      videoUrl: 'https://tczlld.com/oss/douyin.mp4',
      videoSize: {
        width: 0,
        height: 0,
      },
      fileId: '',
      videoElementSize: {
        width: 0,
        height: 0,
      },
      canvas: null,
      ctx: null,
      isDrawing: false,
      rect: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
      },
      noWaterVideoUrl: ""
    }
  },
  mounted() {
    // 这里���立即调用 initCanvas，等到 uploadVideo 被调用后再调用
    // this.initCanvas();
  },
  methods: {
    chooseFile() {
      // 调用系统的文件选择器
      uni.chooseFile({
        count: 1, // 默认选择一个文件
        success: (chooseFileRes) => {
          // 获取选择的文件
          const tempFilePath = chooseFileRes.tempFilePaths[0];
          this.uploadFile(tempFilePath);
        },
        fail: (error) => {
          console.error('选择文件失败:', error);
          this.uploadMessage = '选择文件失败。';
        }
      });
    },
    uploadFile(filePath) {
      const uploadTask = uni.uploadFile({
        url: 'http://localhost/openai/oss/files', // 替换为你的文件上传 API 地址
        filePath: filePath,
        name: 'file',
        success: (uploadFileRes) => {
          console.log(uploadFileRes);
          const response = JSON.parse(uploadFileRes.data); // 假设返回的是 JSON 格式
          if (response.code == 200) {
            uni.showToast({
              title: '文件上传成功！',
              icon: 'success',
              duration: 2000
            });
            console.log('文件上传成功:', response.data);
            this.videoUrl = response.data.url;
            this.fileId = response.data.fileId;
            // this.$nextTick(() => {
            // 	// 确保 DOM 渲染完毕后再初始化 canvas
            // });
            // 调用另一个后台方法
            // this.callBackendMethod(data.fileId); // 传递文件 ID（假设 API 返回了 fileId）
          } else {
            uni.showToast({
              title: '文件上传失败。',
              icon: 'none',
              duration: 2000
            });
            console.error('上传失败:', data.message);
          }
        },
        fail: (error) => {
          console.error('上传文件时发生错误:', error);
          uni.showToast({
            title: '上传过程中发生错误。',
            icon: 'none',
            duration: 2000
          });
        }
      });

      // 可以监听上传进度
      uploadTask.onProgressUpdate((progress) => {
        console.log('上传进度:', progress.progress);
      });
    },

    initCanvas(event) {
      this.videoSize.width = event.detail.width
      this.videoSize.height = event.detail.height
      // 首先获取 uni-canvas 元素
      const uniCanvasElement = document.getElementById('video-canvas');

      // 检查 uni-canvas 是否存在
      if (uniCanvasElement) {
        // 找到嵌套的 canvas 元素
        this.canvas = uniCanvasElement.querySelector('canvas');

        // 调试输出
        console.log('Inner Canvas element:', this.canvas);

        // 确保获取到的确实是一个 canvas
        if (this.canvas && this.canvas instanceof HTMLCanvasElement) {
          this.ctx = this.canvas.getContext('2d');
          console.log('Rendering context obtained:', this.ctx);
        } else {
          console.error('Failed to obtain a valid canvas element.');
          return; // 提前退出方法，避免后续代码报错
        }
      } else {
        console.error('uni-canvas element not found with ID video-canvas');
      }

      // 设置视频和 canvas 的宽高
      const video = this.$refs.videoRef.$el
      const canvas = this.$refs.canvasRef.$el
      console.log("canvas", canvas)

      const videoOffsetWidth = video.offsetWidth
      const videoOffsetHeight = video.offsetHeight

      console.log("this.videoElement",videoOffsetWidth)
      console.log("this.videoElement", videoOffsetHeight)
      const aspectRatio = this.videoSize.width / this.videoSize.height;
      const videoAspectRatio = videoOffsetWidth /videoOffsetHeight;
      console.log("aspectRatio", aspectRatio)
      console.log("videoAspectRatio", videoAspectRatio)
      if (aspectRatio < videoAspectRatio) {
        // 说明视频的高度比较小
        const scale = videoOffsetHeight / this.videoSize.height;
        const videoWidth = this.videoSize.width * scale;
        const videoHeight = this.videoSize.height * scale;
        const videoX = (videoOffsetWidth- videoWidth) / 2;
        console.log("videoX", videoX)

        const videoY = 0;

        canvas.style.width = videoWidth + 'px';
        canvas.style.height = videoHeight + 'px';
        canvas.style.left = videoX + 'px';
        canvas.style.top = videoY + 'px';
        canvas.style.border = '1px solid red'; // 便于调试 canvas 位置


      } else {
        // 说明视频的宽度比较小
        const scale = videoOffsetWidth / this.videoSize.width;
        const videoWidth = this.videoSize.width * scale;
        const videoHeight = this.videoSize.height * scale;
        const videoX = 0;
        const videoY = (videoOffsetHeight - videoHeight) / 2;

        canvas.style.width = videoWidth + 'px';
        canvas.style.height = videoHeight + 'px';
        canvas.style.left = videoX + 'px';
        canvas.style.top = videoY + 'px';
        canvas.style.border = '1px solid red'; // 便于调试 canvas 位置

      }


      console.log("videosize", this.videoSize)


      // this.canvas.style.width = this.videoElement.style.width; // 设置canvas的宽度与video标签一致
      // this.canvas.style.height = this.videoElement.style.height; // ��置canvas的高度与video标签一致
      // 事件处理逻辑
      this.$refs.canvasRef.$el.addEventListener('mousedown', this.startDrawing);
      this.$refs.canvasRef.$el.addEventListener('mousemove', this.draw);
      this.$refs.canvasRef.$el.addEventListener('mouseup', this.stopDrawing);

    },


    startDrawing(e) {
      console.log("start drawing")
      this.isDrawing = true;
      this.rect.x = e.offsetX; // 使用 offsetX 和 offsetY
      this.rect.y = e.offsetY;
    },
    draw(e) {
      if (this.isDrawing) {
        this.rect.width = e.offsetX - this.rect.x;
        this.rect.height = e.offsetY - this.rect.y;
        this.drawRect();
      }
    },
    stopDrawing() {
      this.isDrawing = false;
    },
    drawRect() {
      console.log("Drawing rectangle");
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.ctx.strokeStyle = 'red';
      this.ctx.lineWidth = 2;
      this.ctx.strokeRect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);
      console.log(this.rect.x, this.rect.y, this.rect.width, this.rect.height)



    },



    clearRect() {
      if (this.canvas && this.ctx) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.rect = {
          x: 0,
          y: 0,
          width: 0,
          height: 0
        };
      }
    },
    async removeWatermark() {
      if (!this.videoUrl) {
        uni.showToast({
          title: '请先上传视频',
          icon: 'none'
        });
        return;
      }

      // if (this.rect.width === 0 || this.rect.height === 0) {
      // 	uni.showToast({
      // 		title: '请先框选水印区域',
      // 		icon: 'none'
      // 	});
      // 	return;
      // }

      try {
        uni.showLoading({
          title: '正在去除水印...',
          mask: true
        });

        // const response = await postVideoRemoveWatermark({
        // 	fileId: this.fileId,
        // 	x: this.rect.x,
        // 	y: this.rect.y,
        // 	width: this.rect.width,
        // 	height: this.rect.height
        // });

        const response = await postVideoRemoveWatermark({
          fileId: this.fileId,
          x: 10,
          y: 10,
          width: 100,
          height: 100
        });

        uni.hideLoading();

        if (response.code === 200 && response.data) {
          this.noWaterVideoUrl = response.data.url;
          uni.showToast({
            title: '去除水印成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '去除水印失败，请检查参数是否正确',
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('去除水印出错:', error);
        uni.showToast({
          title: '去除水印出错，请稍后重试',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
</script>


<style scoped>
.input-section {
  margin-bottom: 20px;
}

.button-container {
  display: flex;
  gap: 5px;
  /* 按钮之间的间距调整为5像素 */
}

.upload-btn,
.remove-watermark-btn,
.clear-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn {
  background-color: #67c23a;
  color: white;
}

.remove-watermark-btn {
  background-color: #e6a23c;
  color: white;
}

.clear-btn {
  background-color: #909399;
  color: white;
}
</style>
